package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.*;
import com.nari.ncps.screen.entity.wholeproduct.QtDpIndustryProfile;
import com.nari.ncps.screen.mapper.coal.CoalOverviewItemMapper;
import com.nari.ncps.screen.service.coal.*;
import com.nari.ncps.screen.service.wholeproduct.QtDpIndustryProfileService;
import com.nari.ncps.screen.vo.coal.CoalBasicInfoVO;
import com.nari.ncps.screen.vo.coal.CoalMineIntroVO;
import com.nari.ncps.screen.vo.coal.CoalTopIndicatorsVO;
import com.nari.ncps.screen.vo.coal.CoalUndergroundPersonnelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 产业总览信息表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalOverviewItemServiceImpl extends ServiceImpl<CoalOverviewItemMapper, CoalOverviewItem> implements CoalOverviewItemService {

    @Autowired
    private QtDpIndustryProfileService industryProfileService;
    
    @Autowired
    private CoalProdoperOsvService coalProdoperOsvService;
    
    @Autowired
    private CoalOpermonEquipUseService coalOpermonEquipUseService;

    @Autowired
    private CoalProdoperOutputService coalProdoperOutputService;

    @Autowired
    private CoalProdoperSalesCalorificService coalProdoperSalesCalorificService;

    @Override
    public CoalTopIndicatorsVO getTopIndicators(Integer year) {
        // 如果未指定年份，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询指定年份的最新数据（按月份降序）
        LambdaQueryWrapper<CoalOverviewItem> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CoalOverviewItem::getYear, year)
                .eq(CoalOverviewItem::getOrgCode, 100360)
               .last("LIMIT 1");
        
        CoalOverviewItem item = this.getOne(wrapper);
        
        // 初始化VO
        CoalTopIndicatorsVO vo = new CoalTopIndicatorsVO();
        
        if (item != null) {
            // 年核定产能：吨 -> 万吨
            if (item.getAnnualCapacity() != null) {
                vo.setAnnualCapacity(item.getAnnualCapacity()
                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
            }

            // 煤炭剩余储量：吨 -> 亿吨
            if (item.getCoalReserves() != null) {
//                vo.setCoalReserves(item.getCoalReserves()
//                        .divide(new BigDecimal("100000000"), 2, RoundingMode.HALF_UP));
                vo.setCoalReserves(item.getCoalReserves());
            }

            // 当前生产总量：吨 -> 万吨
//            if (item.getCurrentProduction() != null) {
//                vo.setCurrentProduction(item.getCurrentProduction()
//                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
//            }

            // 当年剥离总量：立方米 -> 万立方米
            if (item.getAnnualStripping() != null) {
                vo.setAnnualStripping(item.getAnnualStripping()
                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
            }

//            // 当年销售总量：吨 -> 万吨
//            if (item.getAnnualSales() != null) {
//                vo.setAnnualSales(item.getAnnualSales()
//                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
//            }

            // 销售总收入：万元 -> 亿元
            if (item.getTotalRevenue() != null) {
                vo.setTotalRevenue(item.getTotalRevenue()
                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
            }

            // 销售总利润：万元 -> 亿元
            if (item.getTotalProfit() != null) {
                vo.setTotalProfit(item.getTotalProfit()
                        .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP));
            }

            // 营业收入利润率：直接使用
            vo.setProfitMargin(item.getProfitMargin().setScale(2, RoundingMode.HALF_UP));

            // 人均利润：直接使用
            vo.setProfitPerCapita(item.getProfitPerCapita());

            // 所得负税率：直接使用
            vo.setTaxRate(item.getTaxRate());
        }

        // 获取 当前生产总量
        LambdaQueryWrapper<CoalProdoperOutput> annualQuery = new LambdaQueryWrapper<>();
        annualQuery.eq(CoalProdoperOutput::getYear, year);
        annualQuery.eq(CoalProdoperOutput::getOrgCode, 100360);
        List<CoalProdoperOutput> annuallist = coalProdoperOutputService.list(annualQuery);
        BigDecimal actTotal = BigDecimal.ZERO;
        if(!annuallist.isEmpty()) {
            actTotal = annuallist.stream().map(CoalProdoperOutput::getAnnualActual).filter(Objects::nonNull).reduce(BigDecimal.ZERO,
                    BigDecimal::add).setScale(2, RoundingMode.HALF_UP);
        }
        vo.setCurrentProduction(actTotal);
       // vo.setCoalReserves(actTotal.divide(new BigDecimal("100000000"), 2, RoundingMode.HALF_UP));

        // 销售总量
        LambdaQueryWrapper<CoalProdoperSalesCalorific> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(CoalProdoperSalesCalorific::getYear, year).eq(CoalProdoperSalesCalorific::getDateType, 0).eq(CoalProdoperSalesCalorific::getOrgCode, "100360");
        List<CoalProdoperSalesCalorific> structureList = coalProdoperSalesCalorificService.list(yearQuery);
        BigDecimal annualSales = BigDecimal.ZERO;            // 年计划完成情况(万吨)
        // 遍历数据进行聚合统计
        for (CoalProdoperSalesCalorific structure : structureList) {
            // 将吨转换为万吨（除以10000）
            BigDecimal volumeInWanTon = structure.getActualSales();
            annualSales = annualSales.add(volumeInWanTon);
        }
        vo.setAnnualSales(annualSales);


        return vo;
    }
    
    @Override
    public CoalMineIntroVO getMineIntro(String orgCode) {
        CoalMineIntroVO vo = new CoalMineIntroVO();
        
        // 根据orgCode查询产业画像表获取矿区简介
        if (orgCode != null && !orgCode.isEmpty()) {
            QtDpIndustryProfile profile = industryProfileService.getByUnitCode(orgCode);
            if (profile != null) {
                vo.setMineName(profile.getUnitName());
                vo.setImageUrl(profile.getImgUrl());
                vo.setIntroduction(profile.getDesc());
            }
            
            // 查询煤炭总览数据获取建矿年份、产能、储量
            LambdaQueryWrapper<CoalOverviewItem> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(CoalOverviewItem::getOrgCode, orgCode)
                   .orderByDesc(CoalOverviewItem::getYear)
                   .orderByDesc(CoalOverviewItem::getMonth)
                   .last("LIMIT 1");
            CoalOverviewItem item = this.getOne(wrapper);
            
            if (item != null) {
                // 年核定产能：吨转换为万吨
                if (item.getAnnualCapacity() != null) {
                    vo.setAnnualCapacity(item.getAnnualCapacity()
                            .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP) + "万吨");
                }
                
                // 煤炭可采储量：吨转换为亿吨
                if (item.getCoalReserves() != null) {
                    vo.setCoalReserves(item.getCoalReserves()
                            .divide(new BigDecimal("100000000"), 2, RoundingMode.HALF_UP) + "亿吨");
                }
                
                // 建矿年份暂无数据，可设置默认值或从其他表获取
                vo.setFoundedYear("1985");
            }
        }
        
        return vo;
    }
    
    @Override
    public CoalBasicInfoVO getBasicInfo(String orgCode) {
        CoalBasicInfoVO vo = new CoalBasicInfoVO();
        
        // 根据orgCode查询煤炭产业总览数据获取基本信息
        if (orgCode != null && !orgCode.isEmpty()) {
            // 查询该单位最新的总览数据
            LambdaQueryWrapper<CoalOverviewItem> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(CoalOverviewItem::getOrgCode, orgCode)
                   .orderByDesc(CoalOverviewItem::getYear)
                   .orderByDesc(CoalOverviewItem::getMonth)
                   .last("LIMIT 1");
            CoalOverviewItem item = this.getOne(wrapper);
            
            if (item != null) {
                vo.setDailyCoalOutput(item.getCurrentProduction());
                vo.setDailyCoalSales(item.getAnnualSales());
                vo.setInventory(item.getCoalReserves());
            }
            
            // 查询土岩剥离量表获取自有和外委剥离量
            int currentYear = LocalDate.now().getYear();
            int currentMonth = LocalDate.now().getMonthValue();
            
            // 查询自有剥离量（unit_type=0, date_type=1表示月度数据）
            LambdaQueryWrapper<CoalProdoperOsv> ownQuery = Wrappers.lambdaQuery();
            ownQuery.eq(CoalProdoperOsv::getOrgCode, orgCode)
                   .eq(CoalProdoperOsv::getYear, currentYear)
                   .eq(CoalProdoperOsv::getMonth, currentMonth)
                   .eq(CoalProdoperOsv::getUnitType, 0)
                   .last("LIMIT 1");
            CoalProdoperOsv ownData = coalProdoperOsvService.getOne(ownQuery);
            
            if (ownData != null && ownData.getMonthlyActual() != null) {
                // 月度数据转换为日均
                vo.setDailyOwnStripping(ownData.getMonthlyActual().divide(new BigDecimal("30"), 2, RoundingMode.HALF_UP));
            } else {
                vo.setDailyOwnStripping(BigDecimal.ZERO);
            }
            
            // 查询外委剥离量（unit_type=1）
            LambdaQueryWrapper<CoalProdoperOsv> outsourceQuery = Wrappers.lambdaQuery();
            outsourceQuery.eq(CoalProdoperOsv::getOrgCode, orgCode)
                         .eq(CoalProdoperOsv::getYear, currentYear)
                         .eq(CoalProdoperOsv::getMonth, currentMonth)
                         .eq(CoalProdoperOsv::getUnitType, 1)
                         .last("LIMIT 1");
            CoalProdoperOsv outsourceData = coalProdoperOsvService.getOne(outsourceQuery);
            
            if (outsourceData != null && outsourceData.getMonthlyActual() != null) {
                vo.setDailyOutsourcedStripping(outsourceData.getMonthlyActual().divide(new BigDecimal("30"), 2, RoundingMode.HALF_UP));
            } else {
                vo.setDailyOutsourcedStripping(BigDecimal.ZERO);
            }
            
            // 计算剥采比 = (自有剥离量 + 外委剥离量) / 煤炭产量
            if (vo.getDailyCoalOutput() != null && vo.getDailyCoalOutput().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal totalStripping = (vo.getDailyOwnStripping() != null ? vo.getDailyOwnStripping() : BigDecimal.ZERO)
                        .add(vo.getDailyOutsourcedStripping() != null ? vo.getDailyOutsourcedStripping() : BigDecimal.ZERO);
                vo.setDailyStrippingRatio(totalStripping.divide(vo.getDailyCoalOutput(), 2, RoundingMode.HALF_UP));
            } else {
                vo.setDailyStrippingRatio(BigDecimal.ZERO);
            }
        }
        
        return vo;
    }
    
    @Override
    public CoalUndergroundPersonnelVO getUndergroundPersonnel(String orgCode) {
        CoalUndergroundPersonnelVO vo = new CoalUndergroundPersonnelVO();
        
        if (orgCode != null && !orgCode.isEmpty()) {
            // 基于设备使用情况估算坑下作业人数
            // 查询该单位的设备使用数据
            int currentYear = LocalDate.now().getYear();
            int currentMonth = LocalDate.now().getMonthValue();
            
            LambdaQueryWrapper<CoalOpermonEquipUse> equipQuery = Wrappers.lambdaQuery();
            equipQuery.eq(CoalOpermonEquipUse::getOrgCode, orgCode)
                     .eq(CoalOpermonEquipUse::getYear, currentYear)
                     .eq(CoalOpermonEquipUse::getMonth, currentMonth)
                     .eq(CoalOpermonEquipUse::getIsUsing, 1); // 只统计启用中的设备
            
            List<CoalOpermonEquipUse> equipList = coalOpermonEquipUseService.list(equipQuery);
            
            // 根据设备数量估算人员数量：
            // 运输车（type=0）：每台3人，电铲（type=2）：每台5人，附属设备（type=1）：每台2人
            int totalPersonnel = 0;
            for (CoalOpermonEquipUse equip : equipList) {
                int count = equip.getEquipmentCount() != null ? equip.getEquipmentCount() : 0;
                int type = equip.getEquipmentType() != null ? equip.getEquipmentType() : 0;
                
                if (type == 0) { // 运输车
                    totalPersonnel += count * 3;
                } else if (type == 2) { // 电铲
                    totalPersonnel += count * 5;
                } else if (type == 1) { // 附属设备
                    totalPersonnel += count * 2;
                }
            }
            
            vo.setPersonnelCount(totalPersonnel);
            
            // 设置统计时间为当前时间
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            vo.setStatisticsTime(formatter.format(now));
            
            // 生成坑下人员名单（基于人数生成模拟名单）
            List<CoalUndergroundPersonnelVO.PersonnelItem> personnelList = new ArrayList<>();
            String[] teams = {"甲班", "乙班", "丙班", "丁班"};
            String[] positions = {"采煤工", "掘进工", "运输工", "电铲操作员", "维修工", "安全员"};
            
            for (int i = 0; i < Math.min(totalPersonnel, 50); i++) { // 最多显示50人
                CoalUndergroundPersonnelVO.PersonnelItem item = new CoalUndergroundPersonnelVO.PersonnelItem();
                item.setName("员工" + String.format("%03d", i + 1));
                item.setTeam(teams[i % teams.length]);
                item.setPosition(positions[i % positions.length]);
                
                // 入井时间：在过去8小时内随机
                LocalDateTime entryTime = now.minusHours(i % 8);
                item.setEntryTime(formatter.format(entryTime));
                
                personnelList.add(item);
            }
            
            vo.setPersonnelList(personnelList);
        }
        
        return vo;
    }
}
